<template>
  <div class="course-page">
    <!-- 顶部导航栏 -->
    <header class="course-header">
      <div class="course-info">
        <h2>{{ course.name }}</h2>
        <p>学分 {{ course.credit }} | 学时 {{ course.hours }} | 课堂访问量 41</p>
        <div class="user-info">
          <el-avatar :src="avatarUrl" size="30"></el-avatar>
          <span>{{ username }}（{{ course.department }}）</span>

          <!-- 课程状态 -->
          <el-tag :type="course.open_status === 1 ? 'success' : 'info'" class="course-status">
            {{ course.open_status === 1 ? "公开" : "私密" }}
          </el-tag>
        </div>
      </div>

      <div class="course-actions">
        <span class="invite-code">邀请码： <b>{{ course.invite_code }}</b></span>
        <el-button type="text" @click="shareCourse">分享课堂</el-button>
        <span>当前身份：{{ role }}</span>

        <!-- 课堂管理 -->
        <el-dropdown trigger="hover">
          <template #default>
            <el-button type="text"> 课堂管理 </el-button>
          </template>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="toggleStatus">
                {{ course.open_status === 1 ? "设为私密" : "设为公开" }}
              </el-dropdown-item>
              <el-dropdown-item @click="deleteCourse" divided>删除课堂</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </header>

    <!-- 成员管理 -->
    <div class="member-management">
      <div class="member-info">
        <el-icon><User /></el-icon> 成员管理 | 学生 {{ course.student_count }} | 教师 {{ course.teacher_count }}
      </div>
      <div class="member-actions">
        <el-button type="primary" @click="addTeacher">添加老师</el-button>
        <el-button type="primary" @click="addAssistant">添加助教</el-button>
        <el-button type="primary" @click="addStudent">添加学生</el-button>
      </div>
    </div>

    <!-- 课程内容 -->
    <div class="course-content">
      <aside class="course-modules">
        <el-menu :default-active="activeModule" @select="handleMenuSelect">
          <el-menu-item
            v-for="module in course.modules"
            :key="module"
            :index="module"
          >
            {{ module }}
          </el-menu-item>
        </el-menu>
      </aside>

      <main class="course-main">
        <el-card v-if="activeModule === '课程设计'">
          <div>
            <el-button type="primary" @click="loadComponent('CourseOutline')">课程目录</el-button>
            <el-button type="primary" @click="loadComponent('TeachingOutline')">教学大纲</el-button>
            <el-button type="primary" @click="loadComponent('TeachingCalendar')" style="margin-left: 10px;">
              教学日历
            </el-button>
          </div>
          <div class="dynamic-content">
            <component :is="currentComponent" :courseName="course.name" />
          </div>
        </el-card>

        <!-- 添加通知公告的动态显示 -->
        <el-card v-if="activeModule === '通知公告'">
          <div class="dynamic-content">
            <NotificationForm />
          </div>
        </el-card>

        <el-card v-else>
          <p>暂无内容</p>
        </el-card>
      </main>
    </div>
  </div>
</template>

<script lang="js">
import axios from "axios";
import TeachingOutline from "./TeachingOutline.vue";
import TeachingCalendar from "./TeachingCalendar.vue";
import CourseOutline from "./CourseOutline.vue";
import NotificationForm from '@/views/notifications/notificationform.vue'; //txg通知界面起
import AllNotifications from '@/views/notifications/allnotifications.vue';
import ClassNotifications from '@/views/notifications/classnotifications.vue';
import UnifiedNotifications from '@/views/notifications/unifiednotifications.vue'; //txg通知界面止
import { ElMessageBox, ElMessage } from "element-plus";

import { reactive, ref, onMounted } from "vue";

export default {
  name: "CoursePage",
  components: {
    TeachingOutline,
    TeachingCalendar,
    CourseOutline,
    NotificationForm,
    AllNotifications,
    ClassNotifications,
    UnifiedNotifications,
  },
  setup() {
    const username = ref("王老师");
    const role = ref("老师");
    const activeModule = ref("课程设计"); // 默认选中课程设计模块
    const currentComponent = ref("CourseOutline"); // 默认组件为课程目录

    const course = reactive({
      name: "加载中...",
      credit: 0,
      hours: 0,
      department: "未知",
      invite_code: "未生成",
      modules: [],
      teacher_count: 0,
      student_count: 0,
      open_status: 0, // 默认私密
    });
    const loadComponent = (componentName) => {
      currentComponent.value = componentName;
    };

    const loadCourseData = async () => {
      //const courseName = decodeURIComponent(window.location.search.split("=")[1] || "默认课程名称").trim();
      const courseName = decodeURIComponent(window.location.search.split("=")[1] || "默认课程名称").trim();

      try {
        const courseResponse = await axios.get(`/course/teachingClass/showBaseInfo`, {
          params: { name: courseName },
        });

        if (courseResponse.data.code === "200") {
          Object.assign(course, courseResponse.data.data);
        } else {
          alert("课程信息加载失败");
        }

        const moduleResponse = await axios.get(`/course/teachingClass/selectModuleByName`, {
          params: { name: courseName },
        });

        if (moduleResponse.data.code === "200") {
          course.modules = moduleResponse.data.data;
          activeModule.value = course.modules.length > 0 ? course.modules[0] : "课程设计";
        } else {
          alert("课程模块加载失败");
        }
      } catch (error) {
        console.error("API请求错误:", error);
        alert("无法获取课程数据");
      }
    };

    onMounted(() => {
      loadCourseData();
    });

    const toggleStatus = async () => {
      const newStatus = course.open_status === 1 ? 0 : 1;

      try {
        const response = await axios.put("course/teachingClass/updateStatus", null, {
          params: { name: course.name, open_status: newStatus }
        });

        console.log("API 响应数据:", response.data);

        if (response.data.code === "200" && response.data.data) {
          course.open_status = response.data.data.open_status;
          console.log("更新后状态:", course.open_status);
          alert(`课程状态已更新为 ${course.open_status === 1 ? "公开" : "私密"}`);
        } else {
          alert("状态更新失败");
        }
      } catch (error) {
        console.error("状态更新失败:", error);
        alert("服务器错误，无法更新状态");
      }
    };

    // 删除课程的逻辑
    const deleteCourse = () => {
      ElMessageBox.confirm(
        '你确定要删除这个课程吗？',
        '提示',
        {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        try {
          // 发起删除请求
          const response = await axios.delete(`/course/teachingClass/deleteByName`, {
            params: { name: course.name },
          });

          if (response.data.code === "200") {
            ElMessage.success('课程已删除');
            // 删除后跳转到首页面
            window.location.href = '/'; //
          } else {
            ElMessage.error('删除课程失败');
          }
        } catch (error) {
          console.error('删除课程时发生错误', error);
          ElMessage.error('网络错误，请稍后再试');
        }
      }).catch(() => {
        ElMessage.info('取消删除');
      });
    };



    // 处理左侧菜单点击事件
    const handleMenuSelect = (index) => {
      activeModule.value = index;
      if (index === "课程设计") {
        currentComponent.value = "CourseOutline"; // 选择课程设计时展示课程目录
      } else if (index === "通知公告") {
        currentComponent.value = "NotificationForm"; // 选择通知公告时展示通知表单
      }
    };

    return {
      username,
      role,
      activeModule,
      currentComponent,
      course,
      handleMenuSelect,
      toggleStatus,
      deleteCourse,
      loadComponent,
    };
  },
};
</script>


<style scoped>
.course-page {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

.course-header {
  background-color: #2a5aa8;
  color: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.member-management {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background: #f5f5f5;
  border-radius: 8px;
  margin-top: 15px;
}

.member-info {
  font-size: 16px;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.member-info .el-icon {
  margin-right: 5px;
}

.member-actions .el-button {
  margin-left: 10px;
}

.course-content {
  display: flex;
  margin-top: 20px;
}

.course-modules {
  width: 20%;
  margin-right: 20px;
}

.course-main {
  flex: 1;
}

.course-status {
  margin-left: 10px;
  font-size: 14px;
  vertical-align: middle;
}

.course-status {
  margin-left: 10px;
  font-size: 14px;
  vertical-align: middle;
}

.course-actions {
  display: flex;
  align-items: center;
  gap: 15px; /* 让每个元素之间有15px的间距 */
}
</style>
